package com.chengww.grab_rp.activities

import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.chengww.grab_rp.R
import com.chengww.grab_rp.base.BaseActivity
import com.chengww.grab_rp.database.AppDatabase
import com.chengww.grab_rp.database.plugin.PluginDao
import com.chengww.grab_rp.database.user.UserDao
import com.chengww.grab_rp.databinding.ActivityHomeBinding
import com.chengww.grab_rp.service.MainService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


/**
 * Created by chengww on 2/20/21
 * @author chengww
 */
class HomeActivity : BaseActivity<HomeViewModel, ActivityHomeBinding>() {
    override fun layoutId() = R.layout.activity_home

    private val userDao: UserDao by lazy { UserDao.getInstance(this) }
    private val pluginDao: PluginDao by lazy { AppDatabase.getInstance(this).pluginDao() }

    override fun provideVM() = HomeViewModel(userDao, AppDatabase.getInstance(this))

    override fun initView() {
        vm.logoutResponse.observe(this) {
            lifecycleScope.launch {
                withContext(Dispatchers.IO) {
                    pluginDao.deleteAll()
                }
                toast(it.msg ?: "")
                stopService(Intent(this@HomeActivity, MainService::class.java))
                LoginActivity.restartApp(this@HomeActivity)
            }
        }

        supportActionBar?.setDisplayShowHomeEnabled(false)
        supportActionBar?.setTitle(R.string.app_name)

        vm.version.value = getVersion()

        v.svService.isChecked = isServiceWorked(MainService::class.java.name)
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.btn_logout -> vm.logout()
            R.id.sv_service -> {
                if (v.svService.isChecked) {
                    val name = startService(Intent(this, MainService::class.java))
                    if (name == null) {
                        v.svService.isChecked = false
                        val message = getString(R.string.warn_toast_service_open_failed)
                        toast(message)
                        return
                    }
                } else {
                    stopService(Intent(this, MainService::class.java))
                }
            }
            R.id.btn_help -> HelpActivity.newIntent(this)
        }
    }

    companion object {
        fun newIntent(activity: Activity) {
            val intent = Intent(activity, HomeActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
            activity.startActivity(intent)
        }
    }

    private fun getVersion(): String {
        return try {
            val manager = this.packageManager
            val info = manager.getPackageInfo(this.packageName, 0)
            info.versionName
        } catch (e: Exception) {
            e.printStackTrace()
            "unknown"
        }
    }

    override fun onBackPressed() {
        moveTaskToBack(true)
    }

    private fun isServiceWorked(serviceName: String): Boolean {
        val myManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        @Suppress("DEPRECATION") val runningService =
            myManager.getRunningServices(1000) as? ArrayList<ActivityManager.RunningServiceInfo>
        if (runningService.isNullOrEmpty()) return false
        for (i in 0 until runningService.size) {
            if (runningService[i].service.className == serviceName) {
                return true
            }
        }
        return false
    }

}